package com.huitong.common.mybatis.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.huitong.common.mybatis.encrypt.EncryptorManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.PreparedStatement;

import static com.huitong.common.mybatis.encrypt.EncryptorManager.HandleType.ENCRYPT;

/**
 * 入参加密拦截器
 *
 * @author fromdrowning
 * @date 2024/4/11 12:17
 */
@Slf4j
@RequiredArgsConstructor
@Intercepts(
    @Signature(type = ParameterHandler.class, method = "setParameters", args = PreparedStatement.class)
)
public class EncryptInterceptor implements Interceptor {

    /**
     * 敏感字段加密算法管理器
     */
    private final EncryptorManager encryptorManager;

    /**
     * 运行原方法
     *
     * @param invocation 被拦截方法的详细信息
     * @return 拦截处理后方法的返回值
     */
    @Override
    public Object intercept(Invocation invocation) {
        return invocation;
    }

    /**
     * 入参加密
     *
     * @param target 入参对象
     * @return 加密后的入参对象
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof ParameterHandler parameterHandler) {
            Object parameterObject = parameterHandler.getParameterObject();
            if (ObjectUtil.isNotNull(parameterObject)) {
                try {
                    encryptorManager.handleFields(parameterObject, ENCRYPT);
                } catch (IllegalAccessException e) {
                    log.error("加密敏感字段时出错", e);
                }
            }
        }

        return target;
    }
}
